package com.bear.atlassianmcp.common.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * MCP端点控制器
 * 提供MCP协议相关的端点和调试信息
 */
@RestController
@RequestMapping("/mcp")
@CrossOrigin(origins = "*")
public class McpController {

    private static final Logger logger = LoggerFactory.getLogger(McpController.class);

    /**
     * MCP服务器信息端点
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getServerInfo() {
        logger.info("MCP info endpoint accessed");
        
        Map<String, Object> info = new HashMap<>();
        info.put("name", "atlassian-mcp-server");
        info.put("version", "1.0.0");
        info.put("description", "Atlassian MCP服务器 - 支持JIRA和Confluence");
        info.put("capabilities", Map.of(
            "tools", true,
            "resources", false,
            "prompts", false
        ));
        info.put("endpoints", Map.of(
            "sse", "/mcp/sse",
            "message", "/mcp/message",
            "info", "/mcp/info",
            "health", "/actuator/health"
        ));
        info.put("supported_systems", Map.of(
            "jira", "7.7.0+",
            "confluence", "6.7.0+"
        ));
        
        return ResponseEntity.ok()
                .header(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*")
                .header(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, OPTIONS")
                .header(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*")
                .body(info);
    }

    /**
     * 预检请求处理
     */
    @RequestMapping(method = RequestMethod.OPTIONS, value = "/**")
    public ResponseEntity<Void> handleOptions() {
        logger.debug("Handling OPTIONS request for MCP endpoint");
        
        return ResponseEntity.ok()
                .header(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*")
                .header(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE, OPTIONS")
                .header(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*")
                .header(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600")
                .build();
    }

    /**
     * 连接测试端点
     */
    @GetMapping("/ping")
    public ResponseEntity<Map<String, Object>> ping() {
        logger.info("MCP ping endpoint accessed");
        
        Map<String, Object> response = new HashMap<>();
        response.put("status", "ok");
        response.put("timestamp", System.currentTimeMillis());
        response.put("server", "atlassian-mcp-server");
        
        return ResponseEntity.ok()
                .header(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*")
                .contentType(MediaType.APPLICATION_JSON)
                .body(response);
    }
}
